﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Bamboo.Utils
{
    /// <summary>
    /// 检查并修复文本文件的字符集问题，只支持GBK
    /// </summary>
    public class CheckGBKEncoding
    {
        Encoding _gbk = Encoding.GetEncoding("gbk");
        Encoding _utf8 = Encoding.GetEncoding("utf-8");

        /// <summary>
        /// 检测字符集，只支持GBK和UTF8。
        /// 支持并发调用
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="fixToGbk">如果检测到UTF8，是否自动修复成GBK</param>
        /// <returns>1-GBK，2-UTF8，3-其他</returns>
        public int DetectEncoding(string filename, bool fixToGbk)
        {
            var bytesOrgi = File.ReadAllBytes(filename);

            string textGbk = _gbk.GetString(bytesOrgi);
            var bytesGbk = _gbk.GetBytes(textGbk);
            if (bytesOrgi.SequenceEqual(bytesGbk)) return 1;

            string textUtf8 = _utf8.GetString(bytesOrgi);
            var bytesUtf8 = _utf8.GetBytes(textUtf8);
            if (bytesOrgi.SequenceEqual(bytesUtf8))
            {
                if (fixToGbk)
                {
                    File.WriteAllText(filename, textUtf8, _gbk);
                }
                return 2;
            }

            return 3;
        }
    }
}
